﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using Camstar.WebClient.Core.WebUtil;
using Camstar.WebClient.WebConstants;

public partial class uMESDocumentViewPopupForm : System.Web.UI.Page
{
    uMESPartReportingBusiness bll = new uMESPartReportingBusiness();
    System.IO.DirectoryInfo _folder;
    FileInfo _file;
    int m_PageSize = 20;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadData();

            if (tvTree.Nodes.Count > 0)
            {
                TreeNode workflowTree = tvTree.Nodes[0].ChildNodes[0];
                upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { PageMethod(upageTurning.CurrentPageIndex, workflowTree); });
            }
        }
    }

    void PageMethod(int index, TreeNode workflowTree)
    {
        wgDoc.Rows.Clear();
        int endNum = index * m_PageSize - 1;//结束行数
        int startNum = index * m_PageSize - m_PageSize;// 起始行数
        workflowTree.ChildNodes.Clear();
        DataTable workflowStepDt = (DataTable)Session["ProcessDocStep"];

        for (int i = startNum; i <= endNum; i++)
        {
            if (i < workflowStepDt.Rows.Count)
            {
                TreeNode workflowStepTree = new TreeNode(); ;
                workflowStepTree.Text = workflowStepDt.Rows[i]["WORKFLOWSTEPNAME"].ToString();
                workflowStepTree.Value = workflowStepDt.Rows[i]["WORKFLOWSTEPID"].ToString() + "-" + workflowStepDt.Rows[i]["SPECID"].ToString();
                workflowTree.ChildNodes.Add(workflowStepTree);
            }
        }

        //给分页控件赋值，用于分页控件信息显示
        upageTurning.TotalRowCount = workflowStepDt.Rows.Count;
        upageTurning.RowCountByPage = m_PageSize;
    }

    protected void tvTree_SelectedNodeChanged(Object sender, System.EventArgs e)
    {
        try
        {
            LoadObjectDocument();
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    //protected void wgDoc_CellEventArgs(object sender, CellEventArgs e)
    //{
    //    try
    //    {
    //        string name = e.Cell.Row.Cells.FromKey("docName").Text;
    //        string rev = e.Cell.Row.Cells.FromKey("DocumentRevision").Text;
    //        OpenDocument(e);
    //    }
    //    catch (Exception ex)
    //    {
    //        DisplayMessage(ex.Message, false);
    //    }
    //}

    protected void LoadData()
    {
        DataTable dt = (DataTable)Session["ProcessDocument"];
        if (dt.Rows.Count == 0)
        {
            return;
        }
              

        DataTable workflowStepDt = bll.GetWorkFlowSetpsByWorkflowID(dt.Rows[0]["WORKFLOWID"].ToString());
        Session.Add("ProcessDocStep", workflowStepDt);// 暂存工序信息
        DataTable workflowDt = bll.GetWorkflowInfobyWorkflowID(dt.Rows[0]["WORKFLOWID"].ToString());
        DataTable productDt = bll.GetProductInfoByID(dt.Rows[0]["PRODUCTID"].ToString());
        if (productDt.Rows.Count == 0 || workflowStepDt.Rows.Count == 0 || workflowDt.Rows.Count == 0)
        {
            DisplayMessage("未查询到相关产品或工艺信息", false);
            return;
        }
        TreeNode productTree = new TreeNode();
        productTree.Text = productDt.Rows[0]["productname"].ToString() + ":" + productDt.Rows[0]["productrevision"].ToString() + ":" + productDt.Rows[0]["description"].ToString();
        productTree.Value = productDt.Rows[0]["productid"].ToString();
        productTree.ToolTip = "产品";

        TreeNode workflowTree = new TreeNode();
        workflowTree.Text = workflowDt.Rows[0]["workflowname"].ToString() + ":" + workflowDt.Rows[0]["workflowrevision"].ToString();
        workflowTree.Value = workflowDt.Rows[0]["WORKFLOWID"].ToString();workflowTree.ToolTip = "工艺";
        productTree.ChildNodes.Add(workflowTree);

        for (int i = 0; i < workflowStepDt.Rows.Count; i++)
        {
            if (i < workflowStepDt.Rows.Count)
            {
                TreeNode workflowStepTree = new TreeNode();
                workflowStepTree.Text = "<span onclick='keepSrollBar()' style='font-size:14px' >" + workflowStepDt.Rows[i]["WORKFLOWSTEPNAME"].ToString() + "</span>";
                workflowStepTree.Value = workflowStepDt.Rows[i]["WORKFLOWSTEPID"].ToString() + "-" + workflowStepDt.Rows[i]["SPECID"].ToString();
                workflowStepTree.ToolTip = "工序";
                workflowTree.ChildNodes.Add(workflowStepTree);
            }
        }

        TreeNode rootTree = new TreeNode();
        if (dt.Columns.Contains("ContainerID"))
        {
            rootTree.Text = dt.Rows[0]["ContainerName"].ToString();
            rootTree.Value = dt.Rows[0]["ContainerID"].ToString();
            rootTree.ToolTip = "批次";

            rootTree.ChildNodes.Add(productTree);
        }
        else {
            rootTree = productTree;
        }

        tvTree.Nodes.Add(rootTree);
        tvTree.ExpandAll();
    }

    /// <summary>
    /// 消息提示
    /// </summary>
    /// <param name="str"></param>
    /// <param name="isOk"></param>
    void DisplayMessage(string str, bool isOk)
    {
        if (isOk == false)
            StatusMessage.ForeColor = Color.Red;
        StatusMessage.Text = "消息：" + str;
    }

    /// <summary>
    /// 附件展示
    /// </summary>
    void LoadObjectDocument()
    {
        StatusMessage.Text = "";
        wgDoc.Rows.Clear();
        int intDepth = tvTree.SelectedNode.Depth;
        string tip = tvTree.SelectedNode.ToolTip;
        DataTable dt = new DataTable();
        //判断点击节点位置
        switch (tip)
        {
            case "产品": //点击图号
                dt = bll.GetObjectDoc("Product", tvTree.SelectedNode.Value);
                break;
            case "工艺": //点击工艺
                dt = bll.GetObjectDoc("Workflow", tvTree.SelectedNode.Value);
                break;
            case "工序"://点击工序
                dt = bll.GetObjectDoc("Spec", tvTree.SelectedNode.Value);
                break;
            case "批次"://点击批次
                dt = bll.GetObjectDoc("Container", tvTree.SelectedNode.Value);
                break;
            default:
                break;
        }

        wgDoc.DataSource = dt;
        wgDoc.DataBind();
    }

    /// <summary>
    /// 文档查看
    /// </summary>
    void OpenDocument(Infragistics.WebUI.UltraWebGrid.CellEventArgs e)
    {
        //attacheddocid
        string strAttachedDocId = string.Empty;
        if (e.Cell.Row.Cells.FromKey("attacheddocid").Value != null)
            strAttachedDocId = e.Cell.Row.Cells.FromKey("attacheddocid").Value.ToString();

        if (strAttachedDocId != null && strAttachedDocId != string.Empty)
        {
            //查询数据库中文档二进制流
            StringBuilder strQuery = new StringBuilder();
            strQuery.Append(@"
                            select docc.doccontent, docc.doccontentsid, atch.attacheddocid , atch.filename
                               from attacheddocs atch
                               left join (SELECT ROWNUM AS RN, d.* FROM doccontents d) docc on atch.doccontentsid = docc.doccontentsid
                            ");

            strQuery.AppendLine("   WHERE atch.attacheddocid = '" + strAttachedDocId + "'");
            DataTable dt = OracleHelper.GetDataTable(strQuery.ToString());
            byte[] doccontent = (byte[])dt.Rows[0]["doccontent"];// dt.Rows[0]["doccontent"] '
            string strDocPath = Server.MapPath(Request.ApplicationPath);
            string strOrgfilename = dt.Rows[0]["filename"].ToString();
            string strSavePath = strDocPath + "\\Temp\\";
            string strFileName = strAttachedDocId + "." + (strOrgfilename.Split('.'))[1].ToString();
            string strPatch = Bytes2File(doccontent, strSavePath, strSavePath + strFileName, strFileName);
            ClientScript.RegisterStartupScript(ClientScript.GetType(), Guid.NewGuid().ToString(), "<script>window.openDocUrl('" + strPatch + "')</script>");
        }
        else
        {
            string strFilePathList = e.Cell.Row.Cells.FromKey("FilePath").Text;
            string strFileName = e.Cell.Row.Cells.FromKey("DocumentName").Text;
            string strDocWebSite = ConfigurationManager.AppSettings["DocWebSite"];
            string strUrl = strDocWebSite + strFileName;

            ClientScript.RegisterStartupScript(ClientScript.GetType(), Guid.NewGuid().ToString(), "<script>window.open('" + strUrl + "','_blank')</script>");
        }

    }

    /// <summary>
    /// 将byte数组转换为文件并保存到指定地址
    /// </summary>
    /// <param name="buff">byte数组</param>
    /// <param name="savepath">保存地址</param>
    /// <param name="filenamePatch"></param>
    /// <param name="fileName"></param>
    /// <returns></returns>
    protected string Bytes2File(Byte[] buff, string savepath, string filenamePatch, string fileName)
    {
        if (System.IO.File.Exists(filenamePatch) == false)
        {
            using (FileStream fs = new FileStream(filenamePatch, FileMode.Create, FileAccess.Write))
            {
                //将字符串写入文件
                fs.Write(buff, 0, buff.Length);
                fs.Flush();
                buff = null;
            }
        }
        return fileName;
    }

    protected void wgDoc_ClickCellButton(object sender, CellEventArgs e)
    {
        try
        {
            string name = e.Cell.Row.Cells.FromKey("docName").Text;
            string rev = e.Cell.Row.Cells.FromKey("DocumentRevision").Text;
            OpenDocument(e);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
}